﻿package com.lin.utils;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import com.lin.views.SdCardManger;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;


public class BitmapUtil {
	Bitmap bitMap;
	int maxSize;
	private Bitmap mDefaultUserIconBitmap;
	private Bitmap mDefaultPostIconBitmap;
	private static String savePath;
	private HashMap<String, SoftReference<Bitmap>> mCacheHashMap = new HashMap<String, SoftReference<Bitmap>>();
	int maxSizeOfFile;

	/*
	 * public BitmapUtil(Bitmap bitmap, int maxSize) { this.bitMap = bitmap;
	 * this.maxSize = maxSize; }
	 */
	public BitmapUtil(Bitmap bitmap, int maxSize, int maxSizeOfFile) {
		this.bitMap = bitmap;
		this.maxSize = maxSize;
		this.maxSizeOfFile = maxSizeOfFile;
	}

	private Context mContext;
	private static BitmapUtil mBitmapUtil;

	public static synchronized BitmapUtil getInstance(Context mContext) {
		if (mBitmapUtil == null) {
			mBitmapUtil = new BitmapUtil(mContext);
			savePath = SdCardManger.getSaveCachePath(mContext);
		}
		return mBitmapUtil;
	}

	public BitmapUtil(Context mContext) {
		this.mContext = mContext;
	}

	public Bitmap imageZoom(String savePath) {
		// 图片允许最大空间 单位：KB
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSizeOfFile) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
		}
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		try {
			bitMap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

			// you can create a new file name "test.jpg" in sdcard folder.
			File f = new File(savePath);
			f.createNewFile();
			// write the bytes in file
			FileOutputStream fo = new FileOutputStream(f);
			fo.write(bytes.toByteArray());
			// remember close de FileOutput

			fo.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitMap;
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	public static String BitMapToString(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		String strBitMap = Base64.encodeToString(b, Base64.DEFAULT);
		return strBitMap;
	}

	/**
	 * 获取屏幕旋转角度
	 * 
	 * @param mContext
	 * @return
	 */
	private static int getRotationDegree(Context mContext) {
		WindowManager mWindowManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		int rotation = mWindowManager.getDefaultDisplay().getRotation();
		// Log.i("tag", "-------------rotation-----------" + rotation);
		switch (rotation) {
		case 0:// 未旋转
			return 0;
		case 1:// 旋转-90
			return 270;
		case 3:// 旋转90
			return 90;
		case 2:// 旋转180
			return 180;
		default:
			return 0;
		}
	}

	public static void GetandSaveCurrentImage2() {
		Process sh;
		try {
			sh = Runtime.getRuntime().exec("su", null, null);

			OutputStream os = sh.getOutputStream();
			byte[] mBytes = ("/system/bin/screencap -p " + "/sdcard/img.jpg")
					.getBytes("ASCII");
			os.write(mBytes);
			os.flush();

			os.close();

			sh.waitFor();

			// then read img.png as bitmap and convert it jpg as follows

			Bitmap screen = BitmapFactory
					.decodeFile(Environment.getExternalStorageDirectory()
							+ File.separator + "img.jpg");

			// my code for saving
			if (screen != null) {
				BitmapUtil mBitmapUtil = new BitmapUtil(screen, 300, 1024);
				screen = mBitmapUtil.imageZoom(Environment
						.getExternalStorageDirectory()
						+ File.separator
						+ "img.jpg");

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Bitmap matrixBitmap(Bitmap mBitmap, DisplayMetrics metrics) {
		float scale = (metrics.widthPixels / 3.0f) / mBitmap.getHeight();
		// Log.i("tag", "-----------------scale--------------" + scale +
		// "==========");
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
		Bitmap bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
				mBitmap.getHeight(), matrix, true);
		if (mBitmap != null && !mBitmap.isRecycled()) {
			mBitmap.recycle();
			System.gc();
		}
		return bitmap;
	}

	/**
	 * 根据传入的新图片的宽度、高度、宽度与高度的比例
	 * @param mBitmap 
	 * @param newWidth 目标图片宽度
	 * @param newHeight 目标图片高度
	 * @param widthProportion 宽度比例
	 * @param heightProportion 高度比例
	 * @return
	 */
	public Bitmap scaleBitmap(Bitmap mBitmap, float newWidth, float newHeight,
			int widthProportion, int heightProportion) {
		if (mBitmap == null) {
			return null;
		}
		int bitmapWid = mBitmap.getWidth();
		int bitmapHei = mBitmap.getHeight();

		Bitmap bitmap = null;
		if (bitmapWid != bitmapHei * widthProportion / heightProportion) {
			int goalLength = 0;
			// if (bitmapHei == newHeight) {
			if (bitmapWid * heightProportion > bitmapHei * widthProportion) {
				goalLength = bitmapHei * widthProportion / heightProportion;
				bitmap = Bitmap.createBitmap(mBitmap,
						(bitmapWid - goalLength) / 2, 0, goalLength, bitmapHei);
			} else if (bitmapWid * heightProportion < bitmapHei * widthProportion) {
				goalLength = bitmapWid * heightProportion / widthProportion;
				bitmap = Bitmap.createBitmap(mBitmap, 0,
						(bitmapHei - goalLength) / 2, bitmapWid, goalLength);
			}
			if (!mBitmap.isRecycled()) {
				mBitmap.recycle();
			}
		} else {
			bitmap = mBitmap;
		}
		float scale = newHeight / bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
		Bitmap cacheBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		if (!bitmap.isRecycled()) {
			bitmap.recycle();
		}
		return cacheBitmap;
	}
	/**
	 * 根据传入的新图片的宽度、高度、宽度与高度的比例
	 * @param mBitmap 
	 * @param newWidth 目标图片宽度
	 * @param newHeight 目标图片高度
	 * @param widthProportion 宽度比例
	 * @param heightProportion 高度比例
	 * @return
	 */
	public Bitmap scaleBitmap(Bitmap mBitmap, float newWidth, float newHeight
			) {
		if (mBitmap == null) {
			return null;
		}
		int bitmapWid = mBitmap.getWidth();
		int bitmapHei = mBitmap.getHeight();
		
		float scale = Math.max(newHeight / bitmapHei, newWidth / bitmapWid);
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
//		Bitmap cacheBitmap = Bitmap.createBitmap(mBitmap, 0, 0,
//				bitmapWid, bitmapHei, matrix, true);
//		if (!mBitmap.isRecycled()) {
//			mBitmap.recycle();
//		}
		return Bitmap.createBitmap(mBitmap, 0, 0,
				bitmapWid, bitmapHei, matrix, true);
	}

	/**
	 * 根据最小尺寸裁剪到所需要的图片
	 * 
	 * @param mBitmap
	 *            要处理的图片
	 * @return
	 */
	private Bitmap accordMinLengthCreateBitmap(Bitmap mBitmap) {
		int bitmapWid = mBitmap.getWidth();
		int bitmapHei = mBitmap.getHeight();
		Bitmap tempBitmap;
		if (bitmapWid < bitmapHei) {
			tempBitmap = Bitmap.createBitmap(mBitmap, 0,
					(bitmapHei - bitmapWid) / 2, bitmapWid, bitmapWid);
		} else {
			tempBitmap = Bitmap.createBitmap(mBitmap,
					(bitmapWid - bitmapHei) / 2, (bitmapHei - bitmapWid) / 2,
					bitmapHei, bitmapHei);
		}

		return tempBitmap;
	}

	/**
	 * 保存视频默认图片
	 * 
	 * @param mBitmap
	 * @param videoDefaultIconUrl
	 */
	public void saveVideoDefaultIcon(Bitmap mBitmap,
			String videoDefaultIconUrl, float newWid) {
		saveFile(mBitmap, videoDefaultIconUrl);
	}

	/**
	 * 获取视频默认图片在本地的链接
	 * 
	 * @param videoDefaultIconUrl
	 * @return
	 */
	public String getVideoDefaultUrl(String videoDefaultIconUrl) {
		File mFile = new File(savePath + File.separator
				+ MD5.getMD5().getMd5(videoDefaultIconUrl) + ".png");
		if (mFile.exists()) {
			return "file://" + mFile.toString();
		}
		return null;
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) {
		try {
			File myCaptureFile = new File(savePath, MD5.getMD5().getMd5(
					fileName)
					+ ".png");
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(myCaptureFile));
			bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 按指定比例缩放加载到的卡牌图片
	 * 
	 * @param mBitmap
	 * @param mContext
	 * @return
	 */
	public  Bitmap bitmapScale(Bitmap mBitmap, Context mContext,
			float newWid, float newHei) {
		int mBitmapHei = mBitmap.getHeight();
		int mBitmapWid = mBitmap.getWidth();
		Matrix matrix = new Matrix();
		float scale = Math.max(newHei / mBitmapHei,
				newWid / mBitmapWid);
		matrix.postScale(scale, scale);
		Bitmap bitmap =  Bitmap.createBitmap(mBitmap, 0, 0, mBitmapWid, mBitmapHei,
				matrix, true);
		if (mBitmap != null && !mBitmap.isRecycled()) {
			mBitmap.recycle();
		}
		return bitmap;
	}
}